// pages/like/like.js
let app = getApp()
var util = require('../../utils/util.js')
var http = require('../../utils/http.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {

    userInfo: null,
    pageCount: 0,
    loadingState: 0,
    inputValue: '',
    pagerList: [],
    currentPage: 1,
    pagersize: 16,
    pagernumber: 0,
    isloadmore: false,
    isRefresh: false,
    isDialogVisible: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      blessing: app.globalData.blessing,
      type: app.globalData.type
    })
  },
  /**
   * 获取页面数据
   */
  getPageData: function () {
    //获取祝福总条数
    let params = {
      pagersize: this.data.pagersize,
      currentPage: this.data.currentPage
    }
    http.get("barragesList", params, false).then(res => {
      console.log(res.data, "res");
      if (res.code == 200) {
        let list = res.data.list
        let total = res.data.total
        if (this.data.isRefresh) {
          this.setData({
            pagerList: list,
            pageCount: total,
            isRefresh: false,
            loadingState: 1
          })

        } else {
          var templist = this.data.pagerList
          var resultlist = templist.concat(list)
          this.setData({
            pagerList: resultlist,
            pageCount: total,
            isRefresh: false,
            loadingState: 1
          })
        }
        console.log(params.pagersize * params.currentPage, total);
        if (params.pagersize * params.currentPage >= total) {
          this.setData({
            isloadmore: true
          })
        } else {
          this.setData({
            isloadmore: false
          })
        }
      } else {
        this.setData({
          isloadmore: true,
          loadingState: 1
        })
      }
    }).catch(res => {
      this.setData({
        loadingState: 1
      })
    })
  },
  bindchooseavatar(e) {


    if (this.data.inputValue == '') {
      wx.showToast({
        title: '祝福语言不能为空哦！',
        icon: "none"
      })
      return
    }
    let nickName = wx.getStorageSync('nickName')
    let avatarUrl = wx.getStorageSync('avatarUrl')
    if (nickName && avatarUrl) {
      this.foo(nickName, avatarUrl)
    } else {
      if (wx.getUserProfile) {
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            nickName = res.userInfo.nickName
            avatarUrl = res.userInfo.avatarUrl
            if (nickName == '微信用户' && avatarUrl == 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132') {
              wx.hideTabBar()
              this.setData({
                isDialogVisible: true
              })
            } else {
              wx.setStorageSync('nickName', nickName)
              wx.setStorageSync('avatarUrl', avatarUrl)
              this.foo(nickName, avatarUrl)
            }
          }
        })
      } else {
        wx.hideTabBar()
        this.setData({
          isDialogVisible: true
        })
      }
    }
  },
  // 关闭弹窗
  handleClose() {
    wx.showTabBar()
    this.setData({
      isDialogVisible: false
    });
  },

  // 处理表单提交
  handleFormSubmit(e) {
    let avatarUrl = e.detail.avatarUrl
    let nickname = e.detail.nickname
    if (this.data.inputValue) {
      this.foo(nickname, avatarUrl)
    }
    wx.setStorageSync('nickName', nickname)
    wx.setStorageSync('avatarUrl', avatarUrl)
  },
  /**
   * 点击重新加载
   */
  reload: function () {

  },


  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      loadingState: 0,
      currentPage: 1,
      isRefresh: true,
      isloadmore: false
    })
    this.getPageData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isloadmore == false) {
      let pager = this.data.currentPage + 1
      this.setData({
        currentPage: pager
      })
      this.getPageData()
    } else {
      wx.showToast({
        title: '暂无更多祝福,快送上您真挚的祝福吧',
        icon: "none"
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    return {
      title: '诚意邀请你参加我们的婚礼',
      imageUrl: app.globalData.imageUrlFinally,
      path: "pages/pics/pics?type=" + app.globalData.type,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享取消',
        })
      }
    }
  },
  //用户点击右上角分享朋友圈
  onShareTimeline: function () {
    return {
      title: '诚意邀请你参加我们的婚礼',
      imageUrl: app.globalData.imageUrlFinally,
      query: 'type=' + app.globalData.type
    }
  },

  /**
   * 提交祝福
   */
  foo(nickname, avatarUrl) {
    let that = this

    wx.showLoading({
      title: '祝福发送中...',
    })
    if (avatarUrl.includes('http')) {
      this.insetBarrages(nickname, avatarUrl)
    } else {
      wx.uploadFile({
        url: app.globalData.requestUrl + '/wxImage',
        filePath: avatarUrl,
        name: 'file',
        formData: {},
        success(res) {
          const data = JSON.parse(res.data);
          avatarUrl = app.globalData.cdnUrl + '/img/' + data.data
          that.insetBarrages(nickname, avatarUrl)
        },
        fail(res) {
          wx.showToast({
            title: '抱歉，您的祝福没有送达哦！请稍后再试。',
            icon: "none"
          })
        }
      });
    }
  },
  insetBarrages(nickname, avatarUrl) {
    let create_time = util.formatTime(new Date())
    let frequency = wx.getStorageSync('frequency') || 0
    if (frequency > 3) {
      wx.showToast({
        title: '对不起您的祝福次数以上线',
        icon: "none"
      })
      return
    }
    let params = {
      title: this.data.inputValue,
      name: nickname,
      avatar: avatarUrl,
      create_time
    }
    http.post("insetBarrages", params, false).then(res => {
      if (res.code == 200) {
        wx.hideLoading()
        wx.hideLoading()
        wx.showToast({
          title: '祝福已送达！',
          icon: "success"
        })
        wx.setStorageSync('frequency',frequency*1+1) 
        this.setData({
          loadingState: 0,
          currentPage: 1,
          inputValue: '',
          isRefresh: true,
          isloadmore: false
        })
        this.getPageData()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '抱歉，您的祝福没有送达哦！请稍后再试。',
          icon: "none"
        })
      }
    }).catch(() => {
      wx.hideLoading()
      wx.showToast({
        title: '抱歉，您的祝福没有送达哦！请稍后再试。',
        icon: "none"
      })
    })
  },
})